package com.example.basecomponent.cityPicker;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;

import androidx.recyclerview.widget.GridLayoutManager;
import com.example.basecomponent.R;
import com.example.basecomponent.TipDialog;
import com.example.basecomponent.cityPicker.adapter.*;
import com.example.basecomponent.cityPicker.adapter.decoration.DividerItemDecoration;
import com.example.basecomponent.cityPicker.adapter.decoration.GridItemDecoration;
import com.example.basecomponent.cityPicker.adapter.decoration.SectionItemDecoration;
import com.example.basecomponent.cityPicker.model.City;
import com.example.basecomponent.cityPicker.model.HotCity;
import com.example.basecomponent.cityPicker.model.LocateState;
import com.example.basecomponent.cityPicker.model.LocatedCity;
import com.example.basecomponent.cityPicker.util.ScreenUtil;
import com.example.basecomponent.cityPicker.view.SideIndexBar;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class CityPickerFragment extends Fragment implements TextWatcher,
        View.OnClickListener, SideIndexBar.OnIndexTouchedChangedListener, InnerListener {

    private View mContentView;
    private RecyclerView mRecyclerView;
    private View mEmptyView;
    private TextView mOverlayTextView;
    private SideIndexBar mIndexBar;
    private EditText mSearchBox;
    private TextView mCancelBtn;
    private ImageView mClearAllBtn;
    private LinearLayout mLinearHistory;
    private ImageView mImageDelete;
    private RecyclerView mRecycleViewHistory;

    private LinearLayoutManager mLayoutManager;
    private CityListAdapter mAdapter;
    private List<City> mAllCities;
    private List<HotCity> mHotCities;
    private List<City> mResults;

    private LocatedCity mLocatedCity;
    private int locateState;
    private OnPickListener mOnPickerListener;
    private OnClearHistoryListener mOnClearListener;
    private JsonParseUtil mJsonParesUtil;
    public boolean isHistoryVisible = false;//true:显示历史数据   false:不显示
    public String cityNames = "",cityCodes = "";
    private GridListAdapter mHistoryAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.cp_fragment_city_picker, container, false);
        return mContentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    private void initViews() {
        mRecyclerView = mContentView.findViewById(R.id.cp_city_recyclerview);
        mLayoutManager = new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new SectionItemDecoration(getActivity(), mAllCities), 0);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity()), 1);
        mAdapter = new CityListAdapter(getActivity(), mAllCities, mHotCities, locateState);
        mAdapter.autoLocate(true);
        mAdapter.setInnerListener(this);
        mAdapter.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                //确保定位城市能正常刷新
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mAdapter.refreshLocationItem();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            }
        });

        mEmptyView = mContentView.findViewById(R.id.cp_empty_view);
        mOverlayTextView = mContentView.findViewById(R.id.cp_overlay);

        mIndexBar = mContentView.findViewById(R.id.cp_side_index_bar);
        mIndexBar.setNavigationBarHeight(ScreenUtil.getNavigationBarHeight(getActivity()));
        mIndexBar.setOverlayTextView(mOverlayTextView)
                .setOnIndexChangedListener(this);

        mSearchBox = mContentView.findViewById(R.id.cp_search_box);
        mSearchBox.addTextChangedListener(this);

        mCancelBtn = mContentView.findViewById(R.id.cp_cancel);
        mClearAllBtn = mContentView.findViewById(R.id.cp_clear_all);
        mCancelBtn.setOnClickListener(this);
        mClearAllBtn.setOnClickListener(this);

        mLinearHistory = mContentView.findViewById(R.id.mLinearHistory);
        mImageDelete = mContentView.findViewById(R.id.mImageDelete);
        mRecycleViewHistory = mContentView.findViewById(R.id.mRecycleViewHistory);
        setHistoryVisible();
        mImageDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mOnClearListener!=null){
                    mOnClearListener.onClear();
                }
            }
        });
    }

    public void clearHistoryData(){
        if(mHistoryAdapter!=null){
            mHistoryAdapter.clearData();
        }
    }

    private void initData() {
        //初始化热门城市
        if (mHotCities == null || mHotCities.isEmpty()) {
            mHotCities = new ArrayList<>();
//            mHotCities.add(new HotCity("苏州市", "suzhou", "320500"));
            mHotCities.add(new HotCity("全部", "quanbu", ""));
            mHotCities.add(new HotCity("上海市", "shanghai", "310100"));
            mHotCities.add(new HotCity("北京市", "beijing", "110100"));
            mHotCities.add(new HotCity("广州市", "guangzhou", "440100"));
            mHotCities.add(new HotCity("成都市", "chengdu", "510100"));
            mHotCities.add(new HotCity("三亚市", "sanya", "460200"));
            mHotCities.add(new HotCity("杭州市", "hangzhou", "330100"));
            mHotCities.add(new HotCity("西安市", "xian", "610100"));
            mHotCities.add(new HotCity("南京市", "nanjing", "320100"));
//            mHotCities.add(new HotCity("厦门市", "xiamen", "350200"));
        }
        
        //初始化定位城市，默认为空时会自动回调定位
//        if (mLocatedCity == null) {
//            mLocatedCity = new LocatedCity(getString(R.string.cp_locating), "未知", "0");
//            locateState = LocateState.LOCATING;
//        } else {
//            locateState = LocateState.SUCCESS;
//        }
        mJsonParesUtil = new JsonParseUtil();
        new CityAsyncTask().execute(getActivity());
    }

    private class CityAsyncTask extends AsyncTask<Context, ProgressBar, List<City>> {

        private final TipDialog progressDialog;

        CityAsyncTask() {
            progressDialog = new TipDialog.Builder(getActivity())
                    .setIconType(TipDialog.Builder.ICON_TYPE_LOADING)
                    .setTipWord("正在加载")
                    .create();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }

        @Override
        protected List<City> doInBackground(Context... context) {
            return mJsonParesUtil.getAllCities(context[0]);
        }

        @Override
        protected void onPostExecute(List<City> cities) {
            super.onPostExecute(cities);
            mAllCities = cities;
            //mAllCities.add(0, mLocatedCity);
            mAllCities.add(0, new HotCity("热门城市", "未知", "0"));
            mResults = mAllCities;
            initViews();
            progressDialog.dismiss();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String keyword = s.toString();
        if (TextUtils.isEmpty(keyword)) {
            mClearAllBtn.setVisibility(View.GONE);
            mEmptyView.setVisibility(View.GONE);
            mResults = mAllCities;
            ((SectionItemDecoration) (mRecyclerView.getItemDecorationAt(0))).setData(mResults);
            mAdapter.updateData(mResults);
        } else {
            mClearAllBtn.setVisibility(View.VISIBLE);
            //开始查找
            mResults = mJsonParesUtil.searchCity(keyword);
            ((SectionItemDecoration) (mRecyclerView.getItemDecorationAt(0))).setData(mResults);
            if (mResults == null || mResults.isEmpty()) {
                mEmptyView.setVisibility(View.VISIBLE);
            } else {
                mEmptyView.setVisibility(View.GONE);
                mAdapter.updateData(mResults);
            }
        }
    }

    //true:显示历史数据   false:不显示
    public void setHistoryVisible(){
        if(isHistoryVisible){
            mLinearHistory.setVisibility(View.VISIBLE);
            List<HotCity> mHotData = new ArrayList<>();
//            mHotData.add(new HotCity("全部","",""));
            if(!cityNames.isEmpty()&&!cityCodes.isEmpty()){
                String[] split1 = cityNames.split(",");
                String[] split2 = cityCodes.split(",");
                for (int i = 0; i < split1.length; i++) {
                    mHotData.add(new HotCity(split1[i],"",split2[i]));
                    if(mHotData.size()==9){
                        break;
                    }
                }
            }
            mRecycleViewHistory.setHasFixedSize(true);
            mRecycleViewHistory.setLayoutManager(new GridLayoutManager(getActivity(),
                    GridListAdapter.SPAN_COUNT, RecyclerView.VERTICAL, false));
            int space = getActivity().getResources().getDimensionPixelSize(R.dimen.cp_grid_item_space);
            mRecycleViewHistory.addItemDecoration(new GridItemDecoration(GridListAdapter.SPAN_COUNT,space));
            mHistoryAdapter = new GridListAdapter(getActivity(), mHotData);
            mHistoryAdapter.setInnerListener(this);
            mRecycleViewHistory.setAdapter(mHistoryAdapter);
        }else{
            mLinearHistory.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.cp_cancel) {
            if (mOnPickerListener != null) {
                mOnPickerListener.onCancel();
            }
            hideAndFinish();
        } else if (id == R.id.cp_clear_all) {
            mSearchBox.setText("");
        }
    }

    @Override
    public void onIndexChanged(String index, int position) {
        mAdapter.scrollToSection(index);
    }

    private void hideAndFinish() {
        if (getActivity() != null) {
            hideSoftInput();
            mSearchBox.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getActivity().finish();
                }
            }, 80);
        }
    }

    @Override
    public void dismiss(int position, City data) {
        if (mOnPickerListener != null) {
            mOnPickerListener.onPick(position, data);
        }
        hideAndFinish();
    }

    public void hideSoftInput() {
        InputMethodManager imm =
                (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.hideSoftInputFromWindow(mSearchBox.getWindowToken(), 0);
    }

    @Override
    public void locate() {
        if (mOnPickerListener != null) {
            mOnPickerListener.onLocate();
        }
    }

    public void setOnPickerListener(OnPickListener listener) {
        this.mOnPickerListener = listener;
    }

    public void setClearHistoryListener(OnClearHistoryListener listener) {
        this.mOnClearListener = listener;
    }

    public void locationChanged(LocatedCity location, int state) {
        mAdapter.updateLocateState(location, state);
    }

    public void setLocatedCity(LocatedCity location) {
        mLocatedCity = location;
    }

    public void setHotCities(List<HotCity> data) {
        if (data != null && !data.isEmpty()) {
            this.mHotCities = data;
            mAdapter.updateHotCities(data);
        }
    }
}
















